let tokenUtil = require('../token');
let redisConst = require('../const/redisConst');
let redis = require('../dao/redis');
let conf = require('../config/config');

const {BusiError, SysError} = require('../exception/exception');

class TokenService {
    constructor() {

    }

    /**
     *
     * @param {String} uid
     * @returns {Promise<String>}
     */
    async updateToken(uid) {
        let tokenObj = {
            uid: uid,
            timestamp: new Date().getTime()
        };

        try {
            let token = tokenUtil.aesEncodeDef(JSON.stringify(tokenObj));
            let cacheKey = redisConst.LOGIN_TOKEN + ":" + uid;
            await redis.set(cacheKey, token);

            return token;
        }catch (e) {
            console.logw("update token err:", e.message, e);
            throw new BusiError(500, e);
        }
    }

    /**
     *
     * @param {String} uid
     * @returns {Promise<String>}
     */
    async getToken(uid) {
        let cacheKey = redisConst.LOGIN_TOKEN + ":" + uid;
        let token = await redis.get(cacheKey);
        return token;
    }

    async validToken(token){
        let tokenDecode = tokenUtil.aesDecodeDef(token);
        let uid = null;
        //增加token解密兼容性
        if(tokenDecode==Number(tokenDecode))
        {
            uid=tokenDecode;
            return uid;
        }
        if (tokenDecode){
            let tokenObj = tokenDecode;
            try {
                tokenObj = JSON.parse(tokenDecode);
                if (tokenObj.uid){
                    uid = tokenObj.uid;
                }
            }catch (e) {

            }
        }

        if (uid === null) {
            throw new BusiError(500, "无效token");
        }

        // let cacheToken = await this.getToken(uid);
        // if (cacheToken && cacheToken !== token) {
        //     console.logw("token已失效, 请重新登录, uid:", uid);
        //     throw new BusiError(500, "token已失效, 请重新登录");
        // }

        return uid;
    }
}

let tokenService = new TokenService();
module.exports = tokenService;
